"""
缺点：需要设置一个默认帧为背景
"""
import cv2
import numpy as np

camera =cv2.VideoCapture(0)

es=cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,3))
kernel=np.ones((5,5),np.uint8)
background=None

while(True):
    ret,frame=camera.read()
    #提取第一帧做为背景
    if background is None:
        ret,frame=camera.read() ##第一次取的图像是黑的，去掉
        background= cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        background=cv2.GaussianBlur(background,(11,11),0)
        continue
    #转为灰度图，高斯平滑
    gray_frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    gray_frame=cv2.GaussianBlur(gray_frame,(11,11),0)

    #计算与背景的差值
    diff = cv2.absdiff(background,gray_frame)
    #阀值化，阀值为25，最大值为255，二值化阀值
    diff =cv2.threshold(diff,25,255,cv2.THRESH_BINARY)[1]
    #进行形态学的膨胀
    #diff = cv2.dilate(diff,es, iterations=2)
    #找到轮廓
    image,cnts,hierarchy=cv2.findContours(diff.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    for c in cnts:
        if cv2.contourArea(c) <1500:
            continue
        (x,y,w,h)=cv2.boundingRect(c)
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)

    cv2.imshow("contours",frame)
    cv2.imshow("dif",diff)
    cv2.imshow("background",background)
    if cv2.waitKey(1000//12) & 0xff==ord("q"):
        break
cv2.destroyAllWindows()
camera.release()